module windumpd.main;

import std.c.windows.windows;
import std.file;
import std.path;
import std.string;
import windump.pathfinder;

//import dotmars.platform.windows.registry;

debug {
	import std.stdio; 
}

import windump.scanning.scanner;

import windump.utf;
import windump.util;
import windump.w32api;
import windump.config;

static const string DefaultReportName = `Report.txt`;

string getDefaultFileName()
{
    return std.path.join(getModulePath, DefaultReportName);
}

debug {

    int main()
    {
		try
		{
        	string result = Scanner.instance.scan();
        	write(getDefaultFileName, result);
		}
		catch(Exception e)
		{
			writefln("EXCEPTION: ", e);
		}
		return 0;
    }

} 
else 
{

	extern (C) void gc_init();
	extern (C) void gc_term();
	extern (C) void _moduleCtor();
	extern (C) void _moduleDtor();

    version(DigitalMars)
	{
        extern (C) void _minit();
        //extern (C) void _moduleUnitTests();
    }
	else version(GNU)
	{
         extern (C) void _STI_monitor_staticctor();
         extern (C) void _STI_critical_init();
	}

    extern (Windows) int WinMain(HINSTANCE hInstance,
            HINSTANCE hPrevInstance,
            LPSTR lpCmdLine,
            int nCmdShow)
    {

        version(DigitalMars)
        {
			gc_init();			// initialize garbage collector
            _minit();			// initialize module constructor table
			_moduleCtor();		// call module constructors

            //_moduleUnitTests();	// run unit tests (optional)
        }
		else version(GNU)
        {
            _STI_monitor_staticctor();
            _STI_critical_init();
            gc_init();
            _moduleCtor();

            //_moduleUnitTests();
        }



		//Anti Debug
		if(IsDebuggerPresent() == TRUE)
			return -1;
        int result = myWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);

        scope(exit)
        {
            _moduleDtor();  // call the dtor of module
            gc_term();			// run finalizers; terminate garbage collector
        }
        return result;
    }

	int myWinMain(HINSTANCE hInstance,
			HINSTANCE hPrevInstance,
			LPSTR lpCmdLine,
			int nCmdShow)
	{
		/* ... insert user code here ... */
		string cmdLine = std.string.toString(lpCmdLine);
		if(cmdLine.length == 0)
			cmdLine = getDefaultFileName;
		
		try
		{
			string result = Scanner.instance.scan();
			write(cmdLine, result);
		}
		catch
		{ 
			//do nothing
		}

		version(WD_DemoEdition)
		{
			string msg = "扫描成功完成！\n\n请注意：\n\t本程序是演示版软件，"
				"只能扫描两位密码，要获得完整功能，请购买正式版。\n\n\n"
				"扫描报告文件位于：" ~ cmdLine
				;
			MessageBoxW(null, toUtf16z(msg), "Windump Demo",
				MB_OK | MB_ICONINFORMATION);
		}

		return 0;
	}

} //debug
